package com.ytd.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;


/**
 * 执行shell脚本工具类
 */
public class CommandExecution {

    public final static String COMMAND_SU = "su";
    public final static String COMMAND_SH = "sh";
    public final static String COMMAND_EXIT = "exit\n";
    public final static String COMMAND_LINE_END = "\n";

    /**
     * Command执行结果
     *
     * @author Mountain
     */
    public static class CommandResult {
        public int result = -1;
        public String errorMsg;
        public String successMsg;
    }

    /**
     * 执行命令—单条
     *
     * @param command
     * @param isRoot
     * @return CommandExecution.execCommand(" 执行的指令 ", " 是否root ");
     */
    public static CommandResult execCommand(String command, boolean isRoot) {
        String[] commands = {command};
        return execCommand(commands, isRoot);
    }

    /**
     * 执行命令-多条
     *
     * @param commands
     * @param isRoot
     * @return
     */
    public static CommandResult execCommand(String[] commands, boolean isRoot) {
        CommandResult commandResult = new CommandResult();
        if (commands == null || commands.length == 0) {
            return commandResult;
        }
        Process process = null;
        DataOutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        try {
            process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command != null) {
                    os.write(command.getBytes());
                    os.writeBytes(COMMAND_LINE_END);
                    os.flush();
                }
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();
            commandResult.result = process.waitFor();
            //获取错误信息
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
            commandResult.successMsg = successMsg.toString();
            commandResult.errorMsg = errorMsg.toString();
            LogUtil.d("command:" + Arrays.toString(commands) + " |result= " + commandResult.result + " |successMsg=" +
                commandResult.successMsg
                + " |errorMsg=" + commandResult.errorMsg);
        } catch (IOException e) {
            String errmsg = e.getMessage();
            if (errmsg != null) {
                LogUtil.d(errmsg);
            } else {
            }
        } catch (Exception e) {
            String errmsg = e.getMessage();
            if (errmsg != null) {
                LogUtil.d(errmsg);
            } else {
            }
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                String errmsg = e.getMessage();
                if (errmsg != null) {
                    LogUtil.d(errmsg);
                } else {
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return commandResult;
    }

    /**
     * 执行命令—单条 不处理返回
     *
     * @return
     */
    static boolean isWait = true;
    static Process processexec = null;

    public static void execCommand(String cmd) {
        try {
            isWait = true;
            processexec = Runtime.getRuntime().exec(cmd);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                        if (isWait) {
                            if (processexec != null) {
                                processexec.destroy();
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }).start();
            processexec.waitFor();
            isWait = false;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (processexec != null) {
                processexec.destroy();
            }
        }
    }
}
